/**
    XML的解析与创建
    @module xml
    @requires elementtree
 */
var CData, ElementTree, element, et, simplebuild, simpleparse, subElement;

et = require('elementtree');

ElementTree = et.ElementTree;

element = et.Element;

subElement = et.SubElement;

CData = et.CData;


/**
    解析简单XML，即只有一层结构（比如微信推送消息）
    @public
    @method simpleparse
    @param {string} xml XML文档的字符串形式
    @returns {object} 解析后的key-value结果
 */

simpleparse = function(xml) {
  var etree, result;
  result = {};
  etree = et.parse(xml);
  etree.iter(null, function(data) {
    result[data.tag] = data.text;
  });
  if ('xml' in result) {
    delete result.xml;
  }
  return result;
};


/**
    从JSON生成简单的XML结构（比如微信推送消息）
    @public
    @method simplebuild
    @param {object} obj JSON数据，只支持简单的key-value
    @param {object} opt xml生成选项，默认utf-8，无描述定义
    @returns {string} XML字符串，非数字内容存于CDATA标签中
 */

simplebuild = function(obj, opt) {
  var etree, item, p, root;
  opt = opt || {
    'xml_declaration': false
  };
  root = element('xml');
  for (p in obj) {
    item = element(p);
    if ((obj[p] === '') || (!isNaN(+obj[p]))) {
      item.text = obj[p];
    } else {
      item.append(CData(obj[p]));
    }
    root.append(item);
  }
  etree = new ElementTree(root);
  return etree.write(opt);
};

module.exports = {
  simpleparse: simpleparse,
  simplebuild: simplebuild
};
